import { Component, ViewChild, ElementRef } from '@angular/core';
import { BlocklyComponent } from './blockly/blockly.component';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
})
export class AppComponent {
  title = 'test-blockly3';

  // Variables for the modal
  showVariableModal: boolean = false;
  systemVariables: any[] = [
    {
      id: 1,
      name: '@Device1.Temperature',
      path: '@Device1.Temperature',
      type: 'number',
    },
    {
      id: 2,
      name: '@Device1.Humidity',
      path: '@Device1.Humidity',
      type: 'number',
    },
    { id: 3, name: '@Device1.Status', path: '@Device1.Status', type: 'string' },
    {
      id: 4,
      name: '@Device2.Temperature',
      path: '@Device2.Temperature',
      type: 'number',
    },
    {
      id: 5,
      name: '@Device2.Pressure',
      path: '@Device2.Pressure',
      type: 'number',
    },
    { id: 6, name: '@System.Time', path: '@System.Time', type: 'date' },
    { id: 7, name: '@System.Date', path: '@System.Date', type: 'date' },
    { id: 8, name: '@System.User', path: '@System.User', type: 'string' },
  ];
  filteredSystemVariables: any[] = [];
  variableSearchTerm: string = '';
  selectedVariable: any = null;

  currentBlock: any = null;

  @ViewChild(BlocklyComponent) blocklyComponent!: BlocklyComponent;
  @ViewChild('fileInput') fileInput!: ElementRef;

  generateCode(): void {
    if (this.blocklyComponent) {
      const code = this.blocklyComponent.generateCode();
      const codeOutput = document.getElementById('codeOutput');
      if (codeOutput) {
        codeOutput.textContent = code;
      }
    }
  }

  runCode(): void {
    if (this.blocklyComponent) {
      this.blocklyComponent.runCode();
    }
  }

  // 保存工作区到 localStorage
  saveWorkspace(): void {
    if (this.blocklyComponent) {
      this.blocklyComponent.saveWorkspace();
      alert('工作区已保存到本地存储');
    }
  }

  // 导出工作区为 XML 文件
  exportWorkspace(): void {
    if (this.blocklyComponent) {
      const xml = this.blocklyComponent.exportWorkspace();

      // 创建 Blob 对象
      const blob = new Blob([xml], { type: 'application/xml' });

      // 创建下载链接
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = 'blockly-workspace.xml';

      // 触发下载
      document.body.appendChild(a);
      a.click();

      // 清理
      setTimeout(() => {
        document.body.removeChild(a);
        URL.revokeObjectURL(url);
      }, 0);
    }
  }

  // 打开文件选择对话框
  importWorkspace(): void {
    this.fileInput.nativeElement.click();
  }

  // 处理文件输入
  handleFileInput(event: Event): void {
    const fileInput = event.target as HTMLInputElement;
    const file = fileInput.files?.[0];

    if (file) {
      const reader = new FileReader();

      reader.onload = (e) => {
        const xmlText = e.target?.result as string;
        if (xmlText && this.blocklyComponent) {
          try {
            this.blocklyComponent.importWorkspace(xmlText);
            alert('工作区已成功导入');
          } catch (error) {
            console.error('导入工作区时出错:', error);
            alert('导入工作区时出错: ' + error);
          }
        }
      };

      reader.readAsText(file);

      // 重置文件输入，以便可以再次选择同一文件
      fileInput.value = '';
    }
  }
  // Variable modal methods
  openVariableModal = (block?: any): void => {
    console.log('Opening variable modal');
    this.currentBlock = block || null;
    this.showVariableModal = true;
    this.filteredSystemVariables = [...this.systemVariables];
    this.variableSearchTerm = '';
    this.selectedVariable = null;
  };

  closeVariableModal() {
    this.showVariableModal = false;
  }

  filterVariables() {
    if (!this.variableSearchTerm) {
      this.filteredSystemVariables = [...this.systemVariables];
      return;
    }

    const searchTerm = this.variableSearchTerm.toLowerCase();
    this.filteredSystemVariables = this.systemVariables.filter((variable) =>
      variable.name.toLowerCase().includes(searchTerm)
    );
  }

  selectVariable(variable: any): void {
    this.selectedVariable = variable;

    // Add the selected variable to the workspace
    if (this.currentBlock) {
      // If a block was provided when opening the modal, use it
      // Logic to apply the selected variable to the block
    } else {
      // Otherwise create a new variable block
      // const xml = `<xml><block type="variables_get"><field name="VAR" id="${variable.id}">${variable.name}</field></block></xml>`;
      // const parser = new DOMParser();
      // const dom = parser.parseFromString(xml, 'text/xml');
      // const block = window.Blockly.Xml.domToBlock(dom.firstChild.firstChild, this.workspace);

      // if (block) {
      //   // Position the new block near the center of the workspace
      //   const metrics = this.workspace.getMetrics();
      //   if (metrics) {
      //     block.moveBy(metrics.viewWidth / 2, metrics.viewHeight / 2);
      //   }
      // }
     this.blocklyComponent.importVariable(variable);
    }

    this.closeVariableModal();
  }

  importSelectedVariable(): void {
    if (!this.selectedVariable) {
      alert('请选择一个变量');
      return;
    }

    console.log('Importing variable:', this.selectedVariable);

    // 创建一个新变量在工作区
    try {
      this.blocklyComponent.importVariable(this.selectedVariable);
      this.closeVariableModal();
      alert('变量已成功引入: ' + this.selectedVariable.name);
    } catch (error) {
      console.error('Error creating variable:', error);
      alert('创建变量时出错: ' + (error as Error).message);
    }
  }
}
